package qj;

import java.io.File;

import qj.util.FileUtil;
import qj.util.LanguageUtil;
import qj.util.RegexUtil;

public class HtmlBrowseIndexer {
	public static void main(String[] args) {
//		index(new File("/Users/quanle/Documents/Microsoft User Data/temp/2/Misc"));
		
		File file = new File("/Users/quanle/Sites/Misc/");
		FileUtil.delete(file);
		FileUtil.copyDir(new File("/Users/quanle/Sites/Misc copy/"), file);
		
		removeMarks(file);
		index(file);
		
	}

	private static void removeMarks(File file) {

		for (File subFile : file.listFiles()) {
			if (subFile.isFile()) {
				continue;
			}
			
			if (subFile.getName().endsWith("_files") && RegexUtil.contains("\\W", subFile.getName())) {
				String newFileName = LanguageUtil.toUrlFriendly(subFile.getName());
				
				subFile.renameTo(new File(subFile.getParentFile(), newFileName));

				File htmlFile = new File(subFile.getParent(), subFile.getName().replaceAll("_files$", "")+ ".html");
				
				if (htmlFile.exists()) {
					String htmlContent = FileUtil.readFileToString(htmlFile, "UTF-8");
					htmlContent = htmlContent.replaceAll(
							"(?:\\./)?\\Q" + subFile.getName() + "\\E", newFileName);
					FileUtil.writeToFile(htmlContent, htmlFile, "UTF-8");
				}
				continue;
			}
			
			removeMarks(subFile);
		}
	}

	private static void index(File file) {
		StringBuilder sb = new StringBuilder();
		
		sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>");
		
		sb.append("<h1>Browse:</h1>");
		for (File subFile : file.listFiles()) {
			if (subFile.isFile()) {
				continue;
			}
			
			sb.append("Dir: <a href=\"" + ( subFile.getName() + "/browse.html") + "\">" + subFile.getName() + "</a><br/>");
			index(subFile);
		}
		for (File subFile : file.listFiles()) {
			if (subFile.isDirectory() || 
					subFile.getName().equals("browse.html") ||
					subFile.getName().startsWith(".")
					) {
				continue;
			}
			sb.append("File: <a href=\"" + subFile.getName() + "\">" + subFile.getName() + "</a><br/>");
		}
		sb.append("</body></html>");
		
		FileUtil.writeToFile(sb.toString(), new File(file, "browse.html"), "UTF-8");
	}
	
	public static class FolderNameChangeTask {
		String targetFile;
		String fromDirName;
		String toDirName;
		public FolderNameChangeTask(String targetFile, String fromDirName,
				String toDirName) {
			this.targetFile = targetFile;
			this.fromDirName = fromDirName;
			this.toDirName = toDirName;
		}
	}
}
